package org.example.core;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.Interval;
import org.antlr.v4.runtime.tree.ParseTree;
import org.example.javaFileGrammar.JavaFileGrammarBaseVisitor;
import org.example.javaFileGrammar.JavaFileGrammarLexer;
import org.example.javaFileGrammar.JavaFileGrammarParser;

import java.io.IOException;
import java.util.Collections;

public class JavaFileVisitor extends JavaFileGrammarBaseVisitor<String> {
    private final StringBuilder outputIR = new StringBuilder();
    private final UtGenHelper utGenHelper = new UtGenHelper();

    public void run() throws IOException {
        System.out.println("Begin...");
        String FileName = "target/classes/Demo.java";

        CharStream inputFile = CharStreams.fromFileName(FileName);
        JavaFileGrammarLexer javaFileLexer = new JavaFileGrammarLexer(inputFile);
        CommonTokenStream tokens = new CommonTokenStream(javaFileLexer);
        JavaFileGrammarParser javaFileParser = new JavaFileGrammarParser(tokens);
        ParseTree tree = javaFileParser.prog();

        visit(tree);

        System.out.println(outputIR);
    }

    @Override
    public String visitFuncDef(JavaFileGrammarParser.FuncDefContext ctx) {
        int textStart = ctx.getStart().getStartIndex();
        int textEnd = ctx.getStop().getStopIndex();
        String funcContent = ctx.start.getInputStream().getText(Interval.of(textStart, textEnd));
        try {
            utGenHelper.accept("Main", Collections.singletonList(funcContent));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return super.visitFuncDef(ctx);
    }
}
